import 'dart:async';

import 'package:flutter/material.dart';
import '../widget/imagePage.dart';

class SwiperPage extends StatefulWidget {
  final double width;
  final double height;
  List<String> list;
  SwiperPage({
    super.key,
    this.width = double.infinity,
    this.height = 200,
    required this.list,
  });

  @override
  State<SwiperPage> createState() => _SwiperPageState();
}

class _SwiperPageState extends State<SwiperPage> {
  int _currentIndex = 0;
  List<Widget> pageList = [];
  late PageController _pageController;
  late Timer timer;
  @override
  void initState() {
    super.initState();
    //PageController
    _pageController = PageController(initialPage: 0);

    //数据
    for (var i = 0; i < widget.list.length; i++) {
      pageList.add(
        ImagePage(
          imageUrl: widget.list[i],
          width: widget.width,
          height: widget.height,
        ),
      );
    }

    //定时器
    timer = Timer.periodic(Duration(seconds: 5), (t) {
      _pageController.animateToPage(
        _currentIndex + 1 % pageList.length,
        duration: Duration(milliseconds: 500),
        curve: Curves.ease,
      );
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: 200,
          child: PageView.builder(
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index % widget.list.length;
              });
            },
            itemCount: 1000,
            itemBuilder: (context, index) {
              return pageList[index % widget.list.length];
            },
          ),
        ),
        Positioned(
          left: 0,
          right: 0, //设置left right0 宽度占满屏幕
          bottom: 2,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(widget.list.length, (index) {
              return Container(
                margin: EdgeInsets.all(5),
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _currentIndex == index ? Colors.blue : Colors.grey,
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}
